package com.raycloud.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class StringUtil {
	public static boolean isInteger(String s) {
		try {
			Integer.valueOf(s);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean isFloat(String s) {
		try {
			Float.valueOf(s);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean isOnlyChinese(String s) {
		Pattern pattern = Pattern.compile("^[\\u4e00-\\u9fa5]+$");
		if (pattern.matcher(s).matches()) {
			return true;
		}
		return false;
	}

	public static String HTMLTagFilter(String str) {
		if (str == null) {
			return null;
		}

		if (str.contains("<") || str.contains("＜")) {
			str = str.replace("<", "&lt;");
			str = str.replace("＜", "&lt;");
		}
		if (str.contains(">") || str.contains("＞")) {
			str = str.replace(">", "&gt;");
			str = str.replace("＞", "&gt;");
		}
		if (str.contains("&")) {
			str = str.replace("&amp;", "&");
		}
		return str;
	}

	public static String getFormatString(String floatValue) {
		int index = floatValue.indexOf(".");
		String leftStr = floatValue.substring(0, index);
		String rightStr = floatValue.substring(index + 1);
		try {
			Integer rightValue = Integer.valueOf(rightStr);
			if (rightValue.intValue() == 0) {
				return leftStr;
			} else {
				return floatValue;
			}
		} catch (Exception e) {
			return "0";
		}
	}

	public static String getFormatString(float floatV) {
		String floatValue = String.valueOf(floatV);
		int index = floatValue.indexOf(".");
		String leftStr = floatValue.substring(0, index);
		String rightStr = floatValue.substring(index + 1);
		try {
			Integer rightValue = Integer.valueOf(rightStr);
			if (rightValue.intValue() == 0) {
				return leftStr;
			} else {
				return floatValue;
			}
		} catch (Exception e) {
			return "0";
		}
	}

	public static String filterMarketingDesc(String desc) {
		String[] strArray = desc
				.split("src=\"http://taojifen.com.cn/img/nibukenenggenwoyiyang.gif\"");
		String e = null;
		if (strArray.length > 1) {
			e = strArray[strArray.length - 1];
			int index = e.indexOf(">");
			e = e.substring(index + 1);
			return e;
		} else {
			return desc;
		}
	}

	public static String getCanChange2IntFromFloat(String v) {
		if (v.contains(".")) {
			String[] vs = v.split("\\.");
			try {
				if (Integer.valueOf(vs[1]) == 0) {
					return vs[0];
				} else {
					return v;
				}
			} catch (Exception e) {
				return v;
			}
		} else {
			return v;
		}
	}

	public static String getExceptionMsg(Throwable e) {
		try {
			String msg = e.getMessage();
			if (msg.contains(":")) {
				int index = msg.indexOf(":");
				msg = msg.substring(index + 1);
				return msg;
			} else {
				return e.getMessage();
			}
		} catch (Exception e1) {
			return e.getMessage();
		}
	}

	/**
	 * 数字小于10在前面补0，凑成至少2位数
	 * 
	 * @param num
	 * @return
	 */
	public static String getNumCheckIsOverTen(int num) {
		return num < 10 ? "0" + num : num + "";
	}

	public static String createPrimaryKey() {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		StringBuilder sb = new StringBuilder();
		sb.append(String.valueOf(c.get(Calendar.YEAR)).substring(2)).append(
				StringUtil.getNumCheckIsOverTen(c.get(Calendar.MONTH) + 1));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.DAY_OF_MONTH)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.HOUR_OF_DAY)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.MINUTE)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.SECOND)));
		String millisecond = c.get(Calendar.MILLISECOND) + "";
		for (int i = 3; i > millisecond.length(); i--) {
			millisecond += "0";
		}
		sb.append(millisecond);
		Random random = new Random();
		int randomNum = random.nextInt(100000);
		String randomS = String.valueOf(randomNum);
		for (int i = 5; i > randomS.length(); i--) {
			randomS = "0" + randomS;
		}
		sb.append(randomS);
		return sb.toString();
	}

	public static String createPrimaryKey(String taobaoId) {

		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(System.currentTimeMillis());
		StringBuilder sb = new StringBuilder();
		sb.append(String.valueOf(c.get(Calendar.YEAR)).substring(2)).append(
				StringUtil.getNumCheckIsOverTen(c.get(Calendar.MONTH) + 1));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.DAY_OF_MONTH)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.HOUR_OF_DAY)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.MINUTE)));
		sb.append(StringUtil.getNumCheckIsOverTen(c.get(Calendar.SECOND)));
		String millisecond = c.get(Calendar.MILLISECOND) + "";
		for (int i = 3; i > millisecond.length(); i--) {
			millisecond += "0";
		}
		sb.append(millisecond);
		// Random random = new Random();
		// int randomNum = random.nextInt(100000);
		// String randomS = String.valueOf(randomNum);
		// for(int i = 5; i > randomS.length(); i--){
		// randomS = "0" + randomS;
		// }
		// sb.append(randomS);
		sb.append(taobaoId.substring(0, 4));
		return sb.toString();
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getUTF8String(String str) {
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String toUnicode(String strText, String code)
			throws UnsupportedEncodingException {
		char c;
		String strRet = "";
		int intAsc;
		String strHex;
		strText = new String(strText.getBytes("ISO-8859-1"), code);
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			if (intAsc > 128) {
				strHex = Integer.toHexString(intAsc);
				strRet = strRet + "&#x" + strHex + ";";
			} else {
				strRet = strRet + c;
			}
		}
		return strRet;
	}

	public static final Map<String, String> DISTANCE_CACHE = new HashMap<String, String>();
	
	public static String toUnicode(String s) {  
        try {  
            StringBuffer out = new StringBuffer("");  
            byte[] bytes = s.getBytes("unicode");  
            for (int i = 2; i < bytes.length - 1; i += 2) { // *  
                out.append("\\u");  
                String str = Integer.toHexString(bytes[i + 1] & 0xff);// **  
                for (int j = str.length(); j < 2; j++) {  
                    out.append("0");// ***  
                }  
                String str1 = Integer.toHexString(bytes[i] & 0xff);  
                out.append(str);  
                out.append(str1);  
            }  
            return out.toString();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
	
	public static String getNumIidFromItemUrl(String itemUrl) {
		Pattern p = Pattern.compile("id=\\d+");
		Matcher m = p.matcher(itemUrl);
		if(m.find()) {
			String s = m.group();
			return s.split("=")[1];
		}
		return null;
	}
	
	public static String getUtf8Enc(String s) {
		try {
			return URLEncoder.encode(s, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getFileNameWithoutSuffix(String fileName) {
		int sepIndex = fileName.lastIndexOf(File.separator);
		int docIndex = fileName.lastIndexOf(".");
		return fileName.substring(sepIndex + 1, docIndex);
	}
	
	public static String replaceFileName(String newFileName, String oldFilePath) {
		int sepIndex = oldFilePath.lastIndexOf(File.separator);
		return oldFilePath.substring(0, sepIndex + 1) + newFileName + "." + FileUtil.getFileSuffix(oldFilePath);
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println(HTMLTagFilter("<script></script>"));
		System.out.println("<script>".replace("<", "&lt;"));
		System.out.println(toUnicode("汪洋汪洋"));
		System.out.println(getFormatString("6.00"));
		System.out.println(getNumIidFromItemUrl("http://item.taobao.com/item.htm?id=5277279250"));
		System.out.println(getFileNameWithoutSuffix("ttt.jpg"));
	}
}
